import axios from 'axios'
import { signUtil, aesUtil, rsaUtil, servePublicKey, privateKey } from 'encryptn'
axios.defaults.timeout = 20000
axios.defaults.baseURL = 'http://8.8.8.8:8080'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*'
// 请求拦截器
axios.interceptors.request.use((config) => {
  // other code here...

  if (config.data) {
    // 生成签名
    const signKey = signUtil(config.data)
    const newSignKey = rsaUtil.ensign(signKey, privateKey)
    // AES随机秘钥
    const romkey = aesUtil.genKey()
    // 服务端公钥对随机秘加密
    const aesKey = rsaUtil.encrypt(romkey, servePublicKey)
    // AES + 随机秘对data体加密
    config.data.sign = newSignKey
    const aesData = aesUtil.encrypt(config.data, romkey)
    const newData = { data: aesData, key: aesKey }
    config.data = newData
  }
  return config
}, (error) => {
  return Promise.reject(error)
})
// 响应拦截器
axios.interceptors.response.use((res) => {
  // other code here

  const { data, key } = res.data
  // 客户端私钥解密key
  const rsaKey = rsaUtil.decrypt(key, privateKey)
  // AES + key解密data
  const newData = aesUtil.decrypt(data, rsaKey)
  // 重新生成签名验证
  if (newData.sign) {
    const copyData = JSON.parse(JSON.stringify(newData))
    delete copyData.sign
    const data = signUtil(copyData)
    const flag = rsaUtil.design(data, newData.sign, servePublicKey)
    // eslint-disable-next-line prefer-promise-reject-errors
    if (!flag) { return Promise.reject({ message: '签名失败' }) }
    return Promise.resolve(res.data)
  } else {
    // eslint-disable-next-line prefer-promise-reject-errors
    return Promise.reject({ message: '请求异常' })
  }
}, (error) => {
  return Promise.reject(error)
})
